﻿using Blog.Core.Api.HostServices;
using Blog.Core.Domain.Model.User;
using Blog.Core.Domain.Values;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Quartz;
using Quartz.Impl;
using System.Drawing.Text;
using System.Reflection;
using Dapper;
using Microsoft.Data.SqlClient;
using Blog.Core.Api.Dapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;

namespace Blog.Core.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {

        [HttpGet("TestQuartZ")]
        public async Task<IActionResult> TestQuartZ()
        {
            //创建调度器
            var scheduler = await new StdSchedulerFactory().GetScheduler();
            await scheduler.Start();//启动
            //创建工作任务
            var job = JobBuilder.Create<FirstJob>().Build();
            //创建触发器
            var trigger = TriggerBuilder.Create()
                .WithCronSchedule("* * * * * ? *")
                .Build();
            //将三个对象连接
            await scheduler.ScheduleJob(job, trigger);
            return Ok();
           
        }
        [HttpGet]
        public async Task<IActionResult> GetByAttbile(string typename)
        {
          
            var t = Assembly.Load("Blog.Core.Services").GetTypes()
                .Where(x => x.Name == typename).FirstOrDefault();
            if (t == null)
            {
                return BadRequest();
            }
            //todo 调查以下怎么获取类里面的构造函数名称 和私有字段
            var list = t.GetConstructors();//获取构造方法
            foreach (var item in list)
            {
                Console.WriteLine("属性名：",item.DeclaringType.Name);
            }
            List<string> names = list.Select(x => x.DeclaringType.Name).ToList();
            return Ok(names);
        }
        /// <summary>
        /// 用反射实现ORM简单例子
        /// </summary>
        /// <param name="typename">输入一个类型的数据，能够自动转换成SQL(以下这个例子，昨天加操作)</param>
        /// <returns></returns>
        [HttpPost("ORM")]
        public async Task<IActionResult> TestORM(Roles role) 
        {
            //1.获取输入参数的类型type
            Type t=role.GetType();
            //2.获取t里的属性名称
           var props= t.GetProperties();//所有属性名称
            //3.拼接SQL语句
            string strsql = $"INSERT INTO {t.Name} VALUES(";
            foreach (var p in props)
            {
                string strValue=p.GetValue(role).ToString();
                strsql = strsql + strValue+',';
            }
            strsql=strsql.TrimEnd(',');
            strsql += ")";
           
            return Ok(strsql);
        }
        //tode：有待研究
        [HttpPost("TestIOC")]
        public async Task<IActionResult> TestIOC(string name)
        {
            //输入类型名称
            var t = Assembly.Load("Blog.Core.Domain").GetTypes();
            //输出一个对象（用反射去动态创建）
            return Ok();
        }
        [HttpGet("FUN1")]
        public string fun1(string str)
        {
            return "调用函数fun1，当前秒：" + str;
        }
        [HttpGet("FUN2")]
        public string fun2(string str)
        {
            return "调用函数fun2，当前秒：" + str;
        }
        [HttpGet("UserList")]
        [AllowAnonymous]
        public IActionResult UserList()
        {
            //1、生成类型，Assembly.Load("命名空间").GetType("命名空间.类名")
            Type type = Assembly.Load("Blog.Core.Api").GetType("Blog.Core.Api.Controllers.ValuesController");
            //获取该类型下的所有私有字段
            //var list = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
            //list[0].GetType();
            //var obj = Activator.CreateInstance(list[0].GetType(), Activator.CreateInstance(typeof(DbContext)));
            //2、实例化这个类型
            //Activator.CreateInstance：//使用最符合指定参数的构造函数创建指定类型的实例。
            object obj = Activator.CreateInstance(type);
            //return Ok(obj);
            //3、建立一个调用方法的类
            MethodInfo method;
            string ss = DateTime.Now.ToString("ss");//当前时间-秒
            if (Convert.ToInt16(ss) % 2 == 0) //秒是偶数的情况
            {
                method = type.GetMethod("fun1"); //根据条件选择要调用的方法
            }
            else
            {
                method = type.GetMethod("fun2");
            }
            //method = type.GetMethod("GetAll");
            //return Ok(method);
            //4、方法的参数，多个参数可以逗号分隔
            object[] para = new object[] { ss };
            //5、调用
            return Ok(method.Invoke(obj, para).ToString());
            //return Ok(DapperHelp.List());
        }
    }
}
